export async function sha256(message: string, salt: string): Promise<string> {
    const msgBuffer = new TextEncoder().encode(message + salt);
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex
}

export async function sha256Compare(plaintext: string,ciphertext: string, salt: string): Promise<boolean> {
    return await sha256(plaintext, salt) === ciphertext;
}

// AES 加密函数
export async function aesEncrypt(plaintext: string, key: string): Promise<string> {
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const encodedText = new TextEncoder().encode(plaintext);

    const cryptoKey = await crypto.subtle.importKey(
        'raw',
        new TextEncoder().encode(key),
        { name: 'AES-GCM', length: 128 },
        false,
        ['encrypt']
    );

    const encryptedContent = await crypto.subtle.encrypt(
        { name: 'AES-GCM', iv },
        cryptoKey,
        encodedText
    );

    const encryptedArray = new Uint8Array(encryptedContent);
    const combined = new Uint8Array(iv.length + encryptedArray.length);
    combined.set(iv);
    combined.set(encryptedArray, iv.length);

    return btoa(String.fromCharCode(...combined));
}

// AES 解密函数
export async function aesDecrypt(ciphertext: string, key: string): Promise<string> {
    const combined = new Uint8Array(
        atob(ciphertext).split('').map(char => char.charCodeAt(0))
    );

    const iv = combined.slice(0, 12);
    const encryptedContent = combined.slice(12);

    const cryptoKey = await crypto.subtle.importKey(
        'raw',
        new TextEncoder().encode(key),
        { name: 'AES-GCM', length: 128 },
        false,
        ['decrypt']
    );

    const decryptedContent = await crypto.subtle.decrypt(
        { name: 'AES-GCM', iv },
        cryptoKey,
        encryptedContent
    );

    return new TextDecoder().decode(decryptedContent);
}

